from flask import request, jsonify, g
from flask_jwt_extended import jwt_required, get_jwt_identity
import datetime
from bson import ObjectId

from app.api.v1 import api_bp
from app import mongo
from app.utils.auth import permission_required
from app.schemas.medical_record import MedicalRecordSchema, MedicalRecordUpdateSchema, MedicalRecordQuerySchema
from app.utils.common import normalize_data, paginate, generate_id

@api_bp.route('/medical-records', methods=['GET'])
@jwt_required()
@permission_required('medical_record:read')
def get_medical_records():
    """获取医疗记录列表"""
    # 获取查询参数
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 20, type=int)
    sort_by = request.args.get('sortBy', 'visitDate')
    order = request.args.get('order', 'desc')
    
    # 构建查询条件
    query = {}
    
    # 获取当前用户信息
    current_user = g.current_user
    user_role = current_user.get('role')
    
    # 基于角色添加访问限制
    if user_role == 'admin' or user_role == 'super_admin':
        # 管理员可以查看所有记录，不添加额外限制
        pass
    elif user_role == 'doctor':
        # 医生只能查看自己的记录或所在科室的记录
        doctor = mongo.db.doctors.find_one({'userId': str(current_user['_id'])})
        if doctor:
            # 如果前端传入了doctorId参数并且不是当前医生的ID，检查是否为同一科室
            request_doctor_id = request.args.get('doctorId')
            if request_doctor_id and request_doctor_id != str(doctor['_id']):
                requested_doctor = mongo.db.doctors.find_one({'_id': ObjectId(request_doctor_id)})
                if requested_doctor and requested_doctor.get('departmentId') != doctor.get('departmentId'):
                    # 如果请求的医生与当前医生不在同一科室，返回错误
                    return jsonify({
                        'success': False,
                        'message': '您无权查看其他科室的医疗记录'
                    }), 403
            
            # 默认只查看自己科室的记录
            if 'departmentId' not in query:
                query['departmentId'] = doctor.get('departmentId')
        else:
            # 用户是医生角色但没有对应的医生档案，限制为只能查看自己创建的记录
            query['createdBy'] = str(current_user['_id'])
    elif user_role == 'nurse':
        # 护士只能查看自己科室的记录
        nurse = mongo.db.users.find_one({'_id': current_user['_id']})
        if nurse and 'departmentId' in nurse:
            query['departmentId'] = nurse['departmentId']
        else:
            # 没有科室信息，限制为只能查看自己创建的记录
            query['createdBy'] = str(current_user['_id'])
    elif user_role == 'patient':
        # 患者只能查看自己的记录
        patient = mongo.db.patients.find_one({'userId': str(current_user['_id'])})
        if patient:
            query['patientId'] = str(patient['_id'])
        else:
            # 用户是患者角色但没有对应的患者档案，返回空结果
            return jsonify({
                'success': True,
                'data': {
                    'total': 0,
                    'page': page,
                    'limit': limit,
                    'records': []
                }
            }), 200
    else:
        # 其他角色只能查看自己创建的记录
        query['createdBy'] = str(current_user['_id'])
    
    # 处理前端传入的过滤条件
    # 按患者ID筛选
    patient_id = request.args.get('patientId')
    if patient_id:
        query['patientId'] = patient_id
    
    # 按医生ID筛选
    doctor_id = request.args.get('doctorId')
    if doctor_id:
        query['doctorId'] = doctor_id
    
    # 按科室ID筛选
    department_id = request.args.get('departmentId')
    if department_id:
        query['departmentId'] = department_id
    
    # 按状态筛选
    status = request.args.get('status')
    if status and status != 'all':
        query['status'] = status
    
    # 按日期范围筛选
    start_date = request.args.get('startDate')
    if start_date:
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            if 'visitDate' not in query:
                query['visitDate'] = {}
            query['visitDate']['$gte'] = start_date
        except ValueError:
            pass
    
    end_date = request.args.get('endDate')
    if end_date:
        try:
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            # 将结束日期设为当天的结束时间
            end_date = end_date.replace(hour=23, minute=59, second=59)
            if 'visitDate' not in query:
                query['visitDate'] = {}
            query['visitDate']['$lte'] = end_date
        except ValueError:
            pass
    
    # 确定排序
    sort_direction = -1 if order.lower() == 'desc' else 1
    
    # 获取数据
    records_cursor = mongo.db.medical_records.find(query).sort(sort_by, sort_direction)
    
    # 分页
    paginated_data = paginate(records_cursor, page, limit)
    
    # 标准化数据并添加患者和医生信息
    records = []
    for record in paginated_data['items']:
        normalized_record = normalize_data(record)
        
        # 获取患者信息
        patient_name = ''
        if 'patientId' in record:
            patient_id = record['patientId']
            if isinstance(patient_id, str) and ObjectId.is_valid(patient_id):
                patient_id = ObjectId(patient_id)
            patient = mongo.db.patients.find_one({'_id': patient_id})
            if patient:
                patient_name = patient.get('name', '')
        normalized_record['patientName'] = patient_name
        
        # 获取医生信息
        doctor_name = ''
        if 'doctorId' in record:
            doctor_id = record['doctorId']
            if isinstance(doctor_id, str) and ObjectId.is_valid(doctor_id):
                doctor_id = ObjectId(doctor_id)
            doctor = mongo.db.doctors.find_one({'_id': doctor_id})
            if doctor:
                doctor_name = doctor.get('name', '')
        normalized_record['doctorName'] = doctor_name
        
        # 获取科室信息
        department_name = ''
        if 'departmentId' in record:
            dept_id = record['departmentId']
            if isinstance(dept_id, str) and ObjectId.is_valid(dept_id):
                dept_id = ObjectId(dept_id)
            department = mongo.db.departments.find_one({'_id': dept_id})
            if department:
                department_name = department.get('name', '')
        normalized_record['departmentName'] = department_name
        
        records.append(normalized_record)
    
    return jsonify({
        'success': True,
        'data': {
            'total': paginated_data['total'],
            'page': paginated_data['page'],
            'limit': paginated_data['per_page'],
            'records': records
        }
    }), 200

@api_bp.route('/medical-records', methods=['POST'])
@jwt_required()
@permission_required('medical_record:create')
def create_medical_record():
    """创建新医疗记录"""
    # 验证请求数据
    schema = MedicalRecordSchema()
    errors = schema.validate(request.json)
    if errors:
        return jsonify({
            'success': False,
            'message': '请求数据验证失败',
            'errors': errors
        }), 400
    
    data = request.json
    
    # 验证患者是否存在
    patient_id = data.get('patientId')
    if not patient_id:
        return jsonify({
            'success': False,
            'message': '患者ID不能为空'
        }), 400
    
    # 验证患者ID格式
    if not ObjectId.is_valid(patient_id):
        return jsonify({
            'success': False,
            'message': f'患者ID格式无效: {patient_id}'
        }), 400
    
    # 检查患者是否存在
    if not mongo.db.patients.find_one({'_id': ObjectId(patient_id)}):
        return jsonify({
            'success': False,
            'message': '患者不存在'
        }), 400
    
    # 验证医生是否存在
    doctor_id = data.get('doctorId')
    if not doctor_id:
        return jsonify({
            'success': False,
            'message': '医生ID不能为空'
        }), 400
    
    # 验证医生ID格式
    if not ObjectId.is_valid(doctor_id):
        return jsonify({
            'success': False,
            'message': f'医生ID格式无效: {doctor_id}'
        }), 400
    
    # 检查医生是否存在
    if not mongo.db.doctors.find_one({'_id': ObjectId(doctor_id)}):
        return jsonify({
            'success': False,
            'message': '医生不存在'
        }), 400
    
    # 验证科室是否存在
    department_id = data.get('departmentId')
    if not department_id:
        return jsonify({
            'success': False,
            'message': '科室ID不能为空'
        }), 400
    
    # 验证科室ID格式
    if not ObjectId.is_valid(department_id):
        return jsonify({
            'success': False,
            'message': f'科室ID格式无效: {department_id}'
        }), 400
    
    # 检查科室是否存在
    if not mongo.db.departments.find_one({'_id': ObjectId(department_id)}):
        return jsonify({
            'success': False,
            'message': '科室不存在'
        }), 400
    
    # 验证visitDate格式
    visit_date = data.get('visitDate')
    if visit_date and isinstance(visit_date, str):
        try:
            # 尝试解析ISO格式的日期
            data['visitDate'] = datetime.datetime.fromisoformat(visit_date.replace('Z', '+00:00'))
        except ValueError:
            try:
                # 尝试其他常见格式
                data['visitDate'] = datetime.datetime.strptime(visit_date, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                return jsonify({
                    'success': False,
                    'message': f'就诊日期格式无效: {visit_date}'
                }), 400
    
    # 生成记录ID
    data['recordId'] = generate_id('MR')
    
    # 设置创建时间和更新时间
    now = datetime.datetime.utcnow()
    data['createdAt'] = now
    data['updatedAt'] = now
    
    # 记录创建者信息
    current_user = g.current_user
    data['createdBy'] = str(current_user['_id'])
    data['createdByName'] = current_user.get('username', '')
    data['createdByRole'] = current_user.get('role', '')
    
    # 默认版本为1
    data['version'] = 1
    
    try:
        # 保存到数据库
        result = mongo.db.medical_records.insert_one(data)
        
        # 获取相关信息用于返回
        patient = mongo.db.patients.find_one({'_id': ObjectId(patient_id)})
        patient_name = patient.get('name', '') if patient else ''
        
        return jsonify({
            'success': True,
            'message': '医疗记录创建成功',
            'data': {
                'id': str(result.inserted_id),
                'recordId': data['recordId'],
                'patientName': patient_name,
                'visitDate': data['visitDate'].isoformat() if isinstance(data['visitDate'], datetime.datetime) else data['visitDate'],
                'createdAt': now.isoformat()
            }
        }), 201
        
    except Exception as e:
        print(f"保存医疗记录时出错: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'保存医疗记录失败: {str(e)}'
        }), 500

@api_bp.route('/medical-records/<id>', methods=['GET'])
@jwt_required()
@permission_required('medical_record:read')
def get_medical_record(id):
    """获取单个医疗记录详情"""
    # 尝试按ID查找
    record = None
    
    # 如果是有效的ObjectId，按_id查找
    if ObjectId.is_valid(id):
        record = mongo.db.medical_records.find_one({'_id': ObjectId(id)})
    
    # 如果没找到，尝试按recordId查找
    if not record:
        record = mongo.db.medical_records.find_one({'recordId': id})
    
    if not record:
        return jsonify({
            'success': False,
            'message': '医疗记录不存在'
        }), 404
    
    # 获取当前用户信息并进行权限检查
    current_user = g.current_user
    user_role = current_user.get('role')
    
    # 检查用户是否有权限查看此记录（复用现有权限检查逻辑）
    if user_role not in ['admin', 'super_admin']:
        # 非管理员需要进行权限检查
        has_permission = False
        
        # 首先检查是否为记录创建者（无论什么角色）
        if record.get('createdBy') == str(current_user['_id']):
            has_permission = True
            print(f"[DEBUG] 权限检查通过: 用户是记录创建者")
        
        elif user_role == 'doctor':
            # 医生可以查看自己创建的记录或自己科室的记录
            # 尝试查找医生档案，支持字符串和ObjectId格式
            doctor = None
            user_id = current_user['_id']
            
            # 首先按ObjectId查询
            if isinstance(user_id, str):
                doctor = mongo.db.doctors.find_one({'userId': user_id})
            else:
                doctor = mongo.db.doctors.find_one({'userId': str(user_id)})
            
            print(f"[DEBUG] 医生档案查询: userId={user_id}, 找到医生: {doctor is not None}")
            
            if doctor:
                # 如果是此医生的记录
                if record.get('doctorId') == str(doctor['_id']):
                    has_permission = True
                    print(f"[DEBUG] 权限检查通过: 医生ID匹配")
                # 或者是同一科室的记录
                elif record.get('departmentId') == doctor.get('departmentId'):
                    has_permission = True
                    print(f"[DEBUG] 权限检查通过: 同科室记录")
            else:
                print(f"[DEBUG] 未找到医生档案，用户ID: {user_id}")
                
        elif user_role == 'nurse':
            # 护士可以查看自己科室的记录或自己创建的记录
            nurse = mongo.db.users.find_one({'_id': current_user['_id']})
            if nurse and 'departmentId' in nurse:
                if record.get('departmentId') == nurse['departmentId']:
                    has_permission = True
                    print(f"[DEBUG] 权限检查通过: 护士同科室记录")
                    
        elif user_role == 'patient':
            # 患者只能查看自己的记录
            patient = mongo.db.patients.find_one({'userId': str(current_user['_id'])})
            if patient and record.get('patientId') == str(patient['_id']):
                has_permission = True
                print(f"[DEBUG] 权限检查通过: 患者自己的记录")
        
        print(f"[DEBUG] 最终权限检查结果: {has_permission}")
        
        # 如果没有权限，返回错误
        if not has_permission:
            print(f"[DEBUG] 权限检查失败详情:")
            print(f"  - 用户角色: {user_role}")
            print(f"  - 用户ID: {current_user['_id']}")
            print(f"  - 记录创建者: {record.get('createdBy')}")
            print(f"  - 记录医生ID: {record.get('doctorId')}")
            print(f"  - 记录科室ID: {record.get('departmentId')}")
            return jsonify({
                'success': False,
                'message': '您无权查看此医疗记录的关联数据'
            }), 403
    
    # 标准化记录数据
    normalized_record = normalize_data(record)
    
    # 获取患者信息
    patient_info = None
    if 'patientId' in record:
        patient_id = record['patientId']
        if isinstance(patient_id, str) and ObjectId.is_valid(patient_id):
            patient_id = ObjectId(patient_id)
        patient = mongo.db.patients.find_one({'_id': patient_id})
        if patient:
            patient_info = {
                'id': str(patient['_id']),
                'patientId': patient.get('patientId', ''),
                'name': patient.get('name', ''),
                'gender': patient.get('gender', ''),
                'age': calculate_age(patient.get('birthDate')),
                'idNumber': patient.get('idNumber', '')
            }
    
    # 获取医生信息
    doctor_info = None
    if 'doctorId' in record:
        doctor_id = record['doctorId']
        if isinstance(doctor_id, str) and ObjectId.is_valid(doctor_id):
            doctor_id = ObjectId(doctor_id)
        doctor = mongo.db.doctors.find_one({'_id': doctor_id})
        if doctor:
            doctor_info = {
                'id': str(doctor['_id']),
                'staffId': doctor.get('staffId', ''),
                'name': doctor.get('name', ''),
                'title': doctor.get('title', '')
            }
    
    # 获取科室信息
    department_info = None
    if 'departmentId' in record:
        dept_id = record['departmentId']
        if isinstance(dept_id, str) and ObjectId.is_valid(dept_id):
            dept_id = ObjectId(dept_id)
        department = mongo.db.departments.find_one({'_id': dept_id})
        if department:
            department_info = {
                'id': str(department['_id']),
                'name': department.get('name', ''),
                'location': department.get('location', '')
            }
    
    # 添加相关信息到记录中
    normalized_record['patientInfo'] = patient_info
    normalized_record['doctorInfo'] = doctor_info
    normalized_record['departmentInfo'] = department_info
    
    return jsonify({
        'success': True,
        'data': normalized_record
    }), 200

@api_bp.route('/medical-records/<id>', methods=['PUT'])
@jwt_required()
@permission_required('medical_record:update')
def update_medical_record(id):
    """更新医疗记录"""
    # 验证请求数据
    schema = MedicalRecordUpdateSchema()
    errors = schema.validate(request.json)
    if errors:
        return jsonify({
            'success': False,
            'message': '请求数据验证失败',
            'errors': errors
        }), 400
    
    data = request.json
    
    # 查找记录
    record = None
    if ObjectId.is_valid(id):
        record = mongo.db.medical_records.find_one({'_id': ObjectId(id)})
    
    if not record:
        record = mongo.db.medical_records.find_one({'recordId': id})
    
    if not record:
        return jsonify({
            'success': False,
            'message': '医疗记录不存在'
        }), 404
    
    # 如果记录已签名，不允许修改
    if record.get('status') == '已签名':
        return jsonify({
            'success': False,
            'message': '已签名的医疗记录不允许修改'
        }), 403
    
    # 获取当前用户信息并进行权限检查
    current_user = g.current_user
    user_role = current_user.get('role')
    
    print(f"[DEBUG] 权限检查开始 - 用户角色: {user_role}, 用户ID: {current_user['_id']}")
    print(f"[DEBUG] 医疗记录信息 - 创建者: {record.get('createdBy')}, 医生ID: {record.get('doctorId')}, 科室ID: {record.get('departmentId')}")
    
    # 检查用户是否有权限更新此记录
    if user_role not in ['admin', 'super_admin']:
        # 非管理员需要进行权限检查
        has_permission = False
        
        if user_role == 'doctor':
            # 医生可以更新自己创建的记录或自己作为主治医生的记录或同科室记录
            
            # 首先检查是否是记录创建者（无论是否有医生档案）
            if record.get('createdBy') == str(current_user['_id']):
                has_permission = True
                print(f"[DEBUG] 权限通过: 是记录创建者")
            else:
                # 尝试查找医生档案（支持字符串和ObjectId两种格式）
                doctor = mongo.db.doctors.find_one({'userId': str(current_user['_id'])})
                if not doctor:
                    # 如果字符串格式没找到，尝试ObjectId格式
                    if ObjectId.is_valid(str(current_user['_id'])):
                        doctor = mongo.db.doctors.find_one({'userId': ObjectId(current_user['_id'])})
                
                print(f"[DEBUG] 查找医生信息: {doctor}")
                
                if doctor:
                    doctor_id = str(doctor['_id'])
                    doctor_dept_id = doctor.get('departmentId')
                    record_doctor_id = record.get('doctorId')
                    record_dept_id = record.get('departmentId')
                    
                    print(f"[DEBUG] 医生ID比较: {doctor_id} vs {record_doctor_id}")
                    print(f"[DEBUG] 科室ID比较: {doctor_dept_id} vs {record_dept_id}")
                    
                    # 检查是否是此医生的记录
                    if record_doctor_id == doctor_id:
                        has_permission = True
                        print(f"[DEBUG] 权限通过: 是医生本人的记录")
                    # 或者是同一科室的记录（医生可以修改同科室记录）
                    elif doctor_dept_id and record_dept_id == doctor_dept_id:
                        has_permission = True
                        print(f"[DEBUG] 权限通过: 同科室记录")
                    # 科室主任可以修改本科室的记录
                    elif doctor.get('isDirector') and record_dept_id == doctor_dept_id:
                        has_permission = True
                        print(f"[DEBUG] 权限通过: 科室主任")
                    else:
                        print(f"[DEBUG] 权限拒绝: 不满足任何条件")
                else:
                    print(f"[DEBUG] 权限拒绝: 未找到医生档案且不是记录创建者")
        elif user_role == 'nurse':
            # 护士只能更新自己创建的记录
            if record.get('createdBy') == str(current_user['_id']):
                has_permission = True
                print(f"[DEBUG] 护士权限通过: 是记录创建者")
        else:
            # 其他角色只能更新自己创建的记录
            if record.get('createdBy') == str(current_user['_id']):
                has_permission = True
                print(f"[DEBUG] 其他角色权限通过: 是记录创建者")
        
        print(f"[DEBUG] 最终权限结果: {has_permission}")
        
        # 如果没有权限，返回错误
        if not has_permission:
            return jsonify({
                'success': False,
                'message': '您无权更新此医疗记录'
            }), 403
    else:
        print(f"[DEBUG] 管理员权限，直接通过")
    
    # 准备更新数据
    update_data = data.copy()
    update_data['updatedAt'] = datetime.datetime.utcnow()
    
    # 记录最后更新者信息
    update_data['updatedBy'] = str(current_user['_id'])
    update_data['updatedByName'] = current_user.get('username', '')
    update_data['updatedByRole'] = current_user.get('role', '')
    
    # 增加版本号
    current_version = record.get('version', 1)
    update_data['version'] = current_version + 1
    
    # 保存之前版本的ID
    if 'previousVersions' not in update_data:
        update_data['previousVersions'] = record.get('previousVersions', [])
    update_data['previousVersions'].append(str(record['_id']))
    
    # 更新数据库
    result = mongo.db.medical_records.update_one(
        {'_id': record['_id']},
        {'$set': update_data}
    )
    
    if result.modified_count == 0:
        return jsonify({
            'success': False,
            'message': '医疗记录更新失败'
        }), 500
    
    return jsonify({
        'success': True,
        'message': '医疗记录更新成功',
        'data': {
            'id': str(record['_id']),
            'recordId': record['recordId'],
            'version': update_data['version'],
            'updatedAt': update_data['updatedAt'].isoformat()
        }
    }), 200

@api_bp.route('/medical-records/<id>/related', methods=['GET'])
@jwt_required()
@permission_required('medical_record:read')
def get_medical_record_related_data(id):
    """获取医疗记录的关联数据（处方+医嘱）"""
    # 首先验证医疗记录是否存在
    record = None
    
    # 如果是有效的ObjectId，按_id查找
    if ObjectId.is_valid(id):
        record = mongo.db.medical_records.find_one({'_id': ObjectId(id)})
    
    # 如果没找到，尝试按recordId查找
    if not record:
        record = mongo.db.medical_records.find_one({'recordId': id})
    
    if not record:
        return jsonify({
            'success': False,
            'message': '医疗记录不存在'
        }), 404
    
    # 获取当前用户信息并进行权限检查
    current_user = g.current_user
    user_role = current_user.get('role')
    
    # 检查用户是否有权限查看此记录（复用现有权限检查逻辑）
    if user_role not in ['admin', 'super_admin']:
        # 非管理员需要进行权限检查
        has_permission = False
        
        # 首先检查是否为记录创建者（无论什么角色）
        if record.get('createdBy') == str(current_user['_id']):
            has_permission = True
            print(f"[DEBUG] 权限检查通过: 用户是记录创建者")
        
        elif user_role == 'doctor':
            # 医生可以查看自己创建的记录或自己科室的记录
            # 尝试查找医生档案，支持字符串和ObjectId格式
            doctor = None
            user_id = current_user['_id']
            
            # 首先按ObjectId查询
            if isinstance(user_id, str):
                doctor = mongo.db.doctors.find_one({'userId': user_id})
            else:
                doctor = mongo.db.doctors.find_one({'userId': str(user_id)})
            
            print(f"[DEBUG] 医生档案查询: userId={user_id}, 找到医生: {doctor is not None}")
            
            if doctor:
                # 如果是此医生的记录
                if record.get('doctorId') == str(doctor['_id']):
                    has_permission = True
                    print(f"[DEBUG] 权限检查通过: 医生ID匹配")
                # 或者是同一科室的记录
                elif record.get('departmentId') == doctor.get('departmentId'):
                    has_permission = True
                    print(f"[DEBUG] 权限检查通过: 同科室记录")
            else:
                print(f"[DEBUG] 未找到医生档案，用户ID: {user_id}")
                
        elif user_role == 'nurse':
            # 护士可以查看自己科室的记录或自己创建的记录
            nurse = mongo.db.users.find_one({'_id': current_user['_id']})
            if nurse and 'departmentId' in nurse:
                if record.get('departmentId') == nurse['departmentId']:
                    has_permission = True
                    print(f"[DEBUG] 权限检查通过: 护士同科室记录")
                    
            # 或者是自己创建的记录
            if record.get('createdBy') == str(current_user['_id']):
                has_permission = True
                print(f"[DEBUG] 权限检查通过: 护士自己创建的记录")
        elif user_role == 'patient':
            # 患者只能查看自己的记录
            patient = mongo.db.patients.find_one({'userId': str(current_user['_id'])})
            if patient and record.get('patientId') == str(patient['_id']):
                has_permission = True
                print(f"[DEBUG] 权限检查通过: 患者自己的记录")
        
        print(f"[DEBUG] 最终权限检查结果: {has_permission}")
        
        # 如果没有权限，返回错误
        if not has_permission:
            print(f"[DEBUG] 权限检查失败详情:")
            print(f"  - 用户角色: {user_role}")
            print(f"  - 用户ID: {current_user['_id']}")
            print(f"  - 记录创建者: {record.get('createdBy')}")
            print(f"  - 记录医生ID: {record.get('doctorId')}")
            print(f"  - 记录科室ID: {record.get('departmentId')}")
            return jsonify({
                'success': False,
                'message': '您无权查看此医疗记录的关联数据'
            }), 403
    
    # 获取记录ID用于查询关联数据
    record_id = str(record['_id'])
    print(f"[DEBUG] 查询关联数据，医疗记录ID: {record_id}")
    
    # 获取关联的处方列表
    prescriptions = []
    try:
        print(f"[DEBUG] 查询处方，条件: {{'medicalRecordId': record_id}}")
        prescriptions_cursor = mongo.db.prescriptions.find({'medicalRecordId': record_id})
        prescriptions_count = 0
        for prescription in prescriptions_cursor:
            normalized_prescription = normalize_data(prescription)
            print(f"[DEBUG] 找到处方: {prescription.get('prescriptionId', 'N/A')}, medicalRecordId: {prescription.get('medicalRecordId', 'N/A')}")
            
            # 获取药品详细信息
            for item in normalized_prescription.get('items', []):
                if 'drugId' in item:
                    drug_id = item['drugId']
                    if isinstance(drug_id, str) and ObjectId.is_valid(drug_id):
                        drug = mongo.db.drugs.find_one({'_id': ObjectId(drug_id)})
                        if drug:
                            item['drugName'] = drug.get('name', '')
                            item['specification'] = drug.get('specification', '')
            
            prescriptions.append(normalized_prescription)
            prescriptions_count += 1
        print(f"[DEBUG] 共找到 {prescriptions_count} 个处方")
    except Exception as e:
        print(f"获取处方数据时出错: {str(e)}")
    
    # 获取关联的医嘱列表
    medical_orders = []
    try:
        print(f"[DEBUG] 查询医嘱，条件: {{'medicalRecordId': record_id}}")
        medical_orders_cursor = mongo.db.medical_orders.find({'medicalRecordId': record_id})
        orders_count = 0
        for order in medical_orders_cursor:
            normalized_order = normalize_data(order)
            print(f"[DEBUG] 找到医嘱: {order.get('orderId', 'N/A')}, medicalRecordId: {order.get('medicalRecordId', 'N/A')}")
            
            # 获取执行者信息
            if 'execution' in normalized_order and 'executedBy' in normalized_order['execution']:
                executor_id = normalized_order['execution']['executedBy']
                if executor_id:
                    if isinstance(executor_id, str) and ObjectId.is_valid(executor_id):
                        executor_id = ObjectId(executor_id)
                    executor = mongo.db.users.find_one({'_id': executor_id})
                    if executor:
                        normalized_order['execution']['executedByName'] = executor.get('name', '')
            
            medical_orders.append(normalized_order)
            orders_count += 1
        print(f"[DEBUG] 共找到 {orders_count} 个医嘱")
    except Exception as e:
        print(f"获取医嘱数据时出错: {str(e)}")
    
    print(f"[DEBUG] 最终返回数据: 处方 {len(prescriptions)} 个, 医嘱 {len(medical_orders)} 个")
    
    # 返回关联数据
    return jsonify({
        'success': True,
        'data': {
            'medicalRecordId': record_id,
            'prescriptions': {
                'total': len(prescriptions),
                'items': prescriptions
            },
            'medicalOrders': {
                'total': len(medical_orders),
                'items': medical_orders
            }
        }
    }), 200

@api_bp.route('/medical-records/appointment/<appointment_id>', methods=['GET'])
@jwt_required()
@permission_required('medical_record:read')
def get_medical_record_by_appointment(appointment_id):
    """通过预约ID获取医疗记录"""
    try:
        print(f"查询预约关联的医疗记录，预约ID: {appointment_id}")
        
        # 验证预约ID格式
        if not appointment_id:
            return jsonify({
                'success': False,
                'message': '预约ID不能为空'
            }), 400
        
        # 构建查询条件 - 通过visitId字段关联
        query = {'visitId': appointment_id}
        
        # 查询医疗记录
        medical_record = mongo.db.medical_records.find_one(query)
        
        if not medical_record:
            print(f"未找到预约 {appointment_id} 关联的医疗记录")
            return jsonify({
                'success': False,
                'message': '未找到相关医疗记录'
            }), 404
        
        print(f"找到医疗记录: {medical_record.get('_id')}")
        
        # 标准化数据
        normalized_record = normalize_data(medical_record)
        
        # 获取患者信息
        if 'patientId' in medical_record:
            patient_id = medical_record['patientId']
            if isinstance(patient_id, str) and ObjectId.is_valid(patient_id):
                patient_id = ObjectId(patient_id)
            patient = mongo.db.patients.find_one({'_id': patient_id})
            if patient:
                normalized_record['patientInfo'] = {
                    'id': str(patient['_id']),
                    'patientId': patient.get('patientId', ''),
                    'name': patient.get('name', ''),
                    'gender': patient.get('gender', ''),
                    'age': patient.get('age', 0),
                    'idNumber': patient.get('idNumber', ''),
                    'phone': patient.get('contactInfo', {}).get('phone', '')
                }
                normalized_record['patientName'] = patient.get('name', '')
        
        # 获取医生信息
        if 'doctorId' in medical_record:
            doctor_id = medical_record['doctorId']
            if isinstance(doctor_id, str) and ObjectId.is_valid(doctor_id):
                doctor_id = ObjectId(doctor_id)
            doctor = mongo.db.doctors.find_one({'_id': doctor_id})
            if doctor:
                normalized_record['doctorInfo'] = {
                    'id': str(doctor['_id']),
                    'staffId': doctor.get('staffId', ''),
                    'name': doctor.get('name', ''),
                    'title': doctor.get('title', '')
                }
                normalized_record['doctorName'] = doctor.get('name', '')
        
        # 获取科室信息
        if 'departmentId' in medical_record:
            dept_id = medical_record['departmentId']
            if isinstance(dept_id, str) and ObjectId.is_valid(dept_id):
                dept_id = ObjectId(dept_id)
            department = mongo.db.departments.find_one({'_id': dept_id})
            if department:
                normalized_record['departmentInfo'] = {
                    'id': str(department['_id']),
                    'name': department.get('name', ''),
                    'location': department.get('location', '')
                }
                normalized_record['departmentName'] = department.get('name', '')
        
        return jsonify({
            'success': True,
            'data': normalized_record
        }), 200
        
    except Exception as e:
        print(f"获取医疗记录失败: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'获取医疗记录失败: {str(e)}'
        }), 500

def calculate_age(birth_date):
    """计算年龄"""
    if not birth_date:
        return None
    
    if isinstance(birth_date, str):
        try:
            birth_date = datetime.datetime.strptime(birth_date, '%Y-%m-%d')
        except ValueError:
            return None
    
    today = datetime.date.today()
    age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
    return age 